from flask import Blueprint, jsonify, request
from ..models import FileStorage

product_bp = Blueprint('product', __name__)
products = FileStorage('products.json')

@product_bp.route('/products', methods=['GET'])
def get_products():
    category = request.args.get('category')
    page = int(request.args.get('page', 1))
    per_page = 10
    
    all_products = products.read()
    
    # 按分类筛选
    if category:
        filtered_products = [p for p in all_products if p.get('category') == category]
    else:
        filtered_products = all_products
    
    # 分页
    start = (page - 1) * per_page
    end = start + per_page
    paginated_products = filtered_products[start:end]
    
    return jsonify({
        'items': [{
            'id': product['id'],
            'title': product['title'],
            'price': product['price'],
            'thumb': product['thumb'],
            'rating': product.get('rating', 0)
        } for product in paginated_products]
    })

@product_bp.route('/products/<int:id>', methods=['GET'])
def get_product_detail(id):
    product = products.find_one('id', id)
    if not product:
        return jsonify({'message': '商品不存在'}), 404
    
    return jsonify({
        'id': product['id'],
        'title': product['title'],
        'description': product['description'],
        'shop': product['shop'],
        'location': product['location'],
        'reviews': product.get('reviews', [])
    })